{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 矢量化加速\n",
    "import time\n",
    "# 计时用装饰器\n",
    "def timer(fun):\n",
    "    def wrapper(*args,**kwargs):\n",
    "        start = time.time()\n",
    "        reault = fun(*args,**kwargs)\n",
    "        end = time.time()\n",
    "        print(f'{fun.__name__} run {end-start} s')\n",
    "        return reault\n",
    "    return wrapper    \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "n = 100000\n",
    "a = torch.ones(n)\n",
    "b = torch.ones(n)\n",
    "c = torch.zeros(n)\n",
    "@timer\n",
    "def vector(a,b):\n",
    "    return a+b\n",
    "\n",
    "@timer\n",
    "def cicle(a,b):\n",
    "    for i in range(n):\n",
    "        c[i] = a[i] + b[i]\n",
    "    return c\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "vector run 0.0010025501251220703 s\n",
      "cicle run 0.6876134872436523 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "tensor([2., 2., 2.,  ..., 2., 2., 2.])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "vector(a,b)\n",
    "cicle(a,b)\n",
    "'''可以看出vector快了很多'''"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
